package com.yuzi.controller.systemCon;

import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.yuzi.common.Constant;
import com.yuzi.common.result.ErRes;
import com.yuzi.common.result.SuRes;
import com.yuzi.controller.BaseCon.BaseController;
import com.yuzi.interceptor.LoginSessionInterceptor;
import com.yuzi.model.systemMo.SysRole;
import com.yuzi.model.systemMo.SysUser;
import com.yuzi.service.systemSer.SysRoleService;
import com.yuzi.shiro.ext.CaptchaFormAuthenticationInterceptor;
import com.yuzi.shiro.ext.CaptchaRender;
import com.yuzi.shiro.ext.CaptchaUsernamePasswordToken;
import com.yuzi.shiro.ext.IncorrectCaptchaException;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ThreadContext;

public class LoginController extends BaseController {

    private static final Logger logger = Logger.getLogger(LoginController.class);
    private static final int DEFAULT_CAPTCHA_LEN = 4;//验证码长度

    private SysRoleService sysRoleService;

    public void index(){
        render(Constant.PageUrl.loginPage);
    }

    @Before(CaptchaFormAuthenticationInterceptor.class)
    public void login(){
        try{
            //authenticationToken：用于封装用户输入的账号信息
            CaptchaUsernamePasswordToken token = this.getAttr("shiroToken");
            //token.setRememberMe(true);        //可能引发错误
            //4.从SecurityUtils工具类中获取subject
            Subject subject = SecurityUtils.getSubject();

            ThreadContext.bind(subject);
            if (subject.isAuthenticated()){
                subject.logout();
                renderJson(SuRes.Res("注销成功，马上跳转到登陆页面!"));
            }else {
                subject.login(token);
                SysUser principal = (SysUser)subject.getPrincipal();
                principal.remove("plaintext");
                if (!"on".equals(principal.get("status"))){
                    subject.logout();
                    renderJson(ErRes.Res("该账号已被禁用，请联系管理员!"));
                    return;
                }
                SysRole sysRole = sysRoleService.findSysRoleByUserId(principal.getInt("id"));
                setSessionAttr(Constant.SessionKey.userKey,principal);
                setSessionAttr(Constant.SessionKey.roleKey,sysRole);
                renderJson(SuRes.Res("登陆成功，马上跳转到主页面!"));
            }
        }catch (IncorrectCaptchaException e) {
            logger.error(e.getMessage());
            renderJson(ErRes.Res(e.getMessage()));
        } catch (LockedAccountException e) {
            logger.error(e.getMessage());
            renderJson(ErRes.Res("账号已被锁定!"));
        } catch (ExcessiveAttemptsException e){
            logger.error(e.getMessage());
            renderJson(ErRes.Res("登陆失败超过5次，请10分钟后再登陆！"));
        } catch (AuthenticationException e) {
            logger.error(e.getMessage());
            renderJson(ErRes.Res(e.getMessage()));
        } catch (Exception e) {
            logger.error(e.getMessage());
            renderJson(ErRes.Res("系统异常!"));
        }
    }

    /**
     * @Title: img
     * @Description: 图形验证码
     * @since V1.0.0
     */
    public void img(){
        CaptchaRender img = new CaptchaRender(DEFAULT_CAPTCHA_LEN);
        this.setSessionAttr(CaptchaRender.DEFAULT_CAPTCHA_MD5_CODE_KEY, img.getMd5RandonCode());
        render(img);
    }
}
